/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import persistencia.entidade.PortalCfg;

/**
 *
 * @author ademar.concrete
 */
public class ImageConverter {

    private static ImageConverter instance = new ImageConverter();

    private ImageConverter() {
    }

    public String toJpgFileTemp(byte[] image) {

        if (image == null) {
            return "";
        }
        return toFile(image, ".jpg");
    }

    public String toPngFileTemp(byte[] image) {
        if (image == null) {
            return "";
        }
        return toFile(image, ".png");
    }

    private String toFile(byte[] image, String sufix) {

        FileOutputStream fos = null;
        try {
            File file = File.createTempFile("img_", sufix);
            if (file.exists()) {
                file.delete();
            }

            fos = new FileOutputStream(file);
            fos.write(image);
            fos.flush();
            fos.close();
            return file.getAbsolutePath().replace("\\", "/");
        } catch (Exception ex) {
            Logger.getLogger(PortalCfg.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(PortalCfg.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return "";
    }

    public String toWbmpFileTemp(byte[] image) {

        if (image == null) {
            return "";
        }

        try {
            String imagePath = toPngFileTemp(image);
            BufferedImage src = ImageIO.read(new File(imagePath));

            int w = src.getWidth();
            int h = src.getHeight();
            BufferedImage dst = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY);
            Graphics2D g2 = dst.createGraphics();
            g2.drawImage(src, 0, 0, null);
            g2.dispose();

            WritableRaster raster = src.getRaster();
            DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();

            return toFile(buffer.getData(), ".wbmp");

        } catch (Exception ex) {
            Logger.getLogger(PortalCfg.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "";
    }
}
